#!/bin/bash
# Copyright (c) 2008,2009,2010 Citrix Systems, Inc.
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License as published
# by the Free Software Foundation; version 2.1 only. with the special
# exception on linking described in file LICENSE.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU Lesser General Public License for more details.
#
. /etc/init.d/functions

FILENAME=`basename $0`
LOCKFILE='/dev/shm/xe_toolstack_restart.lock'

(
flock -x -n 200
if [ "$?" != 0 ]; then 
	echo "Exiting: cannot lock $LOCKFILE. Is an instance of $0 running already?"
	exit 1
fi

echo "Executing $FILENAME"

POOLCONF=`cat @ETCDIR@/pool.conf`
if [ $POOLCONF == "master" ]; then MPATHALERT="mpathalert"; else MPATHALERT=""; fi
SERVICES="perfmon xapi v6d xenopsd xenopsd-xc xenopsd-xenlight
  xenopsd-simulator xenopsd-libvirt xcp-rrdd-iostat xcp-rrdd-squeezed
  xcp-rrdd-xenpm xcp-rrdd-gpumon xcp-rrdd xcp-networkd squeezed forkexecd
  $MPATHALERT xapi-storage-script xapi-clusterd varstored-guard message-switch"

tmp_file=$(mktemp --suffix="xe-toolstack-restart")
systemctl stop stunnel@xapi > $tmp_file 2>&1
kill_stunnel_exit_code=$?
if [[ $kill_stunnel_exit_code != 0 ]]; then
  printf "\nFailed to kill stunnel processes! Output:\n"
  cat $tmp_file
  printf "\n"
fi
rm -f $tmp_file

TO_RESTART=""
for svc in $SERVICES ; do
	# restart services only if systemd said they were enabled
	systemctl is-enabled $svc >/dev/null 2>&1

	if [ $? -eq 0 ] ; then
		TO_RESTART="$svc $TO_RESTART"
		systemctl stop $svc
	fi
done

set -e

for svc in $TO_RESTART ; do
	systemctl start $svc
done

rm -f $LOCKFILE
echo "done."
)200>$LOCKFILE

exit $?
